package com.ruoyi.web.controller.datainterface;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.jm.CertStruct;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;

import static com.ruoyi.common.utils.Base64Utils.ESSGetBase64Decode;
import static com.ruoyi.common.utils.Base64Utils.ESSGetBase64Encode;
import static com.ruoyi.common.utils.file.FileUtils.File2byte;
import static com.ruoyi.common.utils.jm.SM2Crypto.CreateUserSM2Pfx;

/**
 * 制作申请Controller
 *
 *
 * @author ess
 * @date 2021-10-25
 */
@Api("重庆数据处理")
@RestController
@RequestMapping("/cq/data")
@Component("CQCron")
public class ChongQingDataController extends BaseController
{
    @Autowired
    private CQDataService cqDataService;
    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private ISealImgService sealImgService;
    @Autowired
    private ICertificateService certificateService;
    @Autowired
    private ISealDetailService sealDetailService;
    @Autowired
    private ISealInfoService sealInfoService;

    /**
     * 做批量处理
     * @return 路由信息
     */
    @PostMapping("/importSeal")
    public AjaxResult importSeal(String sealName,String imgBase64,int imgW,
                                 int imgH,  String unitId,  String sealTypeId,
                                 String standard,  String personId)
    {
//        unit.setSysDepId(unitId);
        SysDept unit = sysDeptMapper.selectSysDepBySysDepId(unitId);

        String Algorithm = "SM2";
        if("4".equals(standard)||"5".equals(standard)||"6".equals(standard)){
            Algorithm = "SHA1withRSA";
        }
        SealImg sealImg = new SealImg();
        sealImg.setImgId(IdUtils.simpleUUID());
        sealImg.setImgData(imgBase64);
        sealImg.setImgW(imgW);
        sealImg.setImgH(imgH);
        sealImg.setImgType("gif");
        sealImgService.insertSealImg(sealImg);

        Certificate certificate =new Certificate();
        certificate.setCertId(IdUtils.simpleUUID());
        certificate.setAlgorithm(Algorithm);
        certificate.setCertId(IdUtils.simpleUUID());
        certificate.setCountry("中国");
        certificate.setProvince(unit.getuProvince());
        certificate.setCity(unit.getuCity());
        certificate.setUnit(unit.getDeptName());
        certificate.setCertName(personId+sealName);
        certificate.setState(0L);
        certificate.setCertState(4L);

        certificateService.createCertificate(certificate);

        SealDetail sealDetail = new SealDetail();
        sealDetail.setSealDetailId(IdUtils.simpleUUID());
        sealDetail.setSealName(sealName);

        sealDetail.setSealCertId(certificate.getCertId());
        sealDetail.setSealImgId(sealImg.getImgId());

        sealDetail.setSealTypeId(sealTypeId);
        sealDetail.setSealPersonId(personId);
        String sealTime = DateUtils.getTime();
        sealDetail.setSealStartTime(sealTime);

//        增加10年
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(sf.parse(sealTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        cal.add(Calendar.YEAR, 10);//增加10年

        sealDetail.setSealEndTime(sf.format(cal.getTime()));
        sealDetail.setIsUk(0L);
        sealDetail.setSealStandard(Integer.valueOf(standard));
        sealDetail.setInputTime(DateUtils.getTime());
        sealDetail.setInputUserId("1");
        sealDetail.setState(0L);
        sealDetailService.insertSealDetail_1(sealDetail);

        SealInfo sealInfo = new SealInfo();
        sealInfo.setSealInfoId(IdUtils.simpleUUID());
        sealInfo.setSealName(sealName);
        sealInfo.setUnitId(String.valueOf(unit.getDeptId()));
        sealInfo.setSealStandard(Integer.valueOf(standard));
        sealInfo.setInputTime(DateUtils.getTime());
        sealInfo.setInputUserId("1");
        sealInfo.setState(0L);
        sealInfo.setJbrCardData("001");
        sealInfo.setJbrCardName("制章系统");
        sealInfo.setJbrCardType("");

        sealInfo.setSealDetailId(sealDetail.getSealDetailId());
        sealInfoService.insertSealInfo(sealInfo);

        return AjaxResult.success(sealInfo.getSealInfoId());
    }
    //    批量手签授权
    @ApiOperation("批量手签授权")
    @GetMapping("/takeSignJur")
    public String takeSignJur()
    {
        Integer resCode = cqDataService.takeSignJur();
        if (resCode==1) {
            return Constants.TAKE_SUCESS;
        }  else {
            return Constants.TAKE_ERRO;
        }
    }

    // 处理重庆人员数据
    @ApiOperation("处理重庆人员数据")
    @GetMapping("/takeCQPersonData")
    public String takeCQPersonData()
//    public String takeCQPersonData1111()
    {
        Integer resCode = cqDataService.takeCQPersonData();
        if (resCode==1) {
            return Constants.TAKE_SUCESS;
        }  else {
            return Constants.TAKE_ERRO;
        }
    }


    // 自动将person表转换业务系统人员数据
    @ApiOperation("自动将person表转换业务系统人员数据")
    @GetMapping("/takeBuSysPersonData")
    public String takeBuSysPersonData()
    {
        Integer resCode = cqDataService.takeBuSysPersonData();
        if (resCode==1) {
            return Constants.TAKE_SUCESS;
        }  else {
            return Constants.TAKE_ERRO;
        }
    }

    //    定时处理重庆人员数据
    public void takeCQPersonDataCron()
//    public void takeCQPersonDataCron1111()
    {
        long begin = System.currentTimeMillis();
        System.out.println("定时处理重庆人员数据 开始时间："+DateUtils.getTime());
        Integer resCode = cqDataService.takeCQPersonData();
        if (resCode==1) {
            System.out.println(Constants.TAKE_SUCESS);
        }  else {
            System.out.println(Constants.TAKE_ERRO);
        }

        long end = System.currentTimeMillis();
        System.out.println("定时处理重庆人员数据 结束时间："+DateUtils.getTime()+";耗时："+(end-begin)/1000+"秒");
    }

    //    定时处理重庆组织机构数据
    public void takeCQOrgInfoCron()
    {
        long begin = System.currentTimeMillis();
        System.out.println("定时处理重庆组织机构数据 开始时间："+DateUtils.getTime());
        Integer resCode = cqDataService.takeCQOrgInfo();
        if (resCode==1) {
            System.out.println(Constants.TAKE_SUCESS);
        }  else {
            System.out.println(Constants.TAKE_ERRO);
        }

        long end = System.currentTimeMillis();
        System.out.println("定时处理重庆组织机构数据 结束时间："+DateUtils.getTime()+";耗时："+(end-begin)/1000+"秒");

    }



    //    处理重庆组织机构数据
    @ApiOperation("处理重庆组织机构数据")
    @GetMapping("/takeCQOrgInfo")
    public String takeCQOrgInfo()
    {
        Integer resCode = cqDataService.takeCQOrgInfo();
        if (resCode==1) {
            return Constants.TAKE_SUCESS;
        }  else {
            return Constants.TAKE_ERRO;
        }
    }


    /**
     * 做批量处理
     * @return 路由信息
     */
    @PostMapping("/exportSeal")
    public AjaxResult importSeal(String savePath){
        List<SealInfo> sealInfoList =  sealInfoService.selectSealInfoList(new SealInfo());
        for (SealInfo sealInfo: sealInfoList) {
            String depName = sealInfo.getSysDeptName();
            String sealName = sealInfo.getSealName();
            String psw = sealInfo.getSealDetail().getCertificate().getCertPsw();
            String pfx = sealInfo.getSealDetail().getCertificate().getPfxBase64();
            String cer = sealInfo.getSealDetail().getCertificate().getCerBase64();
            String img = sealInfo.getSealDetail().getSealImg().getImgData();
            //创建文件夹
            String path = savePath+"\\"+depName+"\\"+sealName+"\\";
            File file = new File(path);
            if (!file.exists()){
                file.mkdirs();
            }
            FileUtils.byte2File(psw.getBytes(StandardCharsets.UTF_8),path+sealName+".txt");
            FileUtils.byte2File(ESSGetBase64Decode(pfx),path+sealName+".pfx");
            FileUtils.byte2File(ESSGetBase64Decode(cer),path+sealName+".cer");
            FileUtils.byte2File(ESSGetBase64Decode(img),path+sealName+".gif");
        }
        return AjaxResult.success("success");
    }

    /**
     * 做批量处理
     * @return 路由信息
     */
    @PostMapping("/ForSynData/GetSealList")
    public AjaxResult GetSealList(){

        List<SealInfo> sealInfoList =  sealInfoService.selectSealInfoList(new SealInfo());
        List<String> sealList = new ArrayList<>();
        for (SealInfo sealInfo: sealInfoList) {
            sealList.add(sealInfo.getSealInfoId());
        }
        return AjaxResult.success(sealList);
    }
    @PostMapping("/ForSynData/GetSealInfo")
    public AjaxResult GetSealInfo(String sealInfoId){
        SealInfo sealInfo =  sealInfoService.selectSealInfoBySealInfoId(sealInfoId);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("SEALID",sealInfo.getSealInfoId());
        jsonObject.put("SEALNAME",sealInfo.getSealName());
        jsonObject.put("WIDTH",sealInfo.getSealDetail().getSealImg().getImgW());
        jsonObject.put("HEIGHT",sealInfo.getSealDetail().getSealImg().getImgH());
        jsonObject.put("IMGDATA",sealInfo.getSealDetail().getSealImg().getImgData());
        jsonObject.put("IMGTYPE",sealInfo.getSealDetail().getSealImg().getImgType());
        jsonObject.put("SEALSTANDARD",sealInfo.getSealDetail().getSealStandard());
        jsonObject.put("CERT",sealInfo.getSealDetail().getCertificate().getCerBase64());
        jsonObject.put("PFXFILE",sealInfo.getSealDetail().getCertificate().getPfxBase64());
        jsonObject.put("PFXPSW",sealInfo.getSealDetail().getCertificate().getCertPsw());
        jsonObject.put("UKTYPE",sealInfo.getSealDetail().getUkType());
        jsonObject.put("UKID",sealInfo.getSealDetail().getUkId());
        jsonObject.put("ASNFILE",sealInfo.getSealDetail().getUsbKeyInfo());

        return AjaxResult.success(jsonObject);
    }

//    public static void main(String[] args) {
//        String sealTime = DateUtils.getTime();
//
////        增加10年
//        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Calendar cal = Calendar.getInstance();
//        try {
//            cal.setTime(sf.parse(sealTime));
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        cal.add(Calendar.YEAR, 10);//增加一年
//
//        System.out.println(sf.format(cal.getTime()));
//    }
}
